<template>
  <div class="mod-config">
    <el-form :inline="true">
      <el-form-item>
        <date-phase ref="datePhase" dateTypeRange="0234" :datePhase="datePhase" ></date-phase>
      </el-form-item>
      <el-form-item label="选择平台" prop="leader">
        <el-select v-model="plat" multiple placeholder="全部平台" style="width:300px;" clearable>
            <el-option
              v-for="item in getUserPlats()"
              :key="item.name"
              :label="item.name"
              :value="item.name">
            </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="负责人">
        <el-select v-model="dingId" placeholder="全部" style="width:100px;" clearable>
            <el-option
              v-for="item in this.b2cMembers"
              :key="item.dingId"
              :label="item.realName"
              :value="item.dingId">
            </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="getReport()" :loading="dataListLoading">查询</el-button>
        <el-button v-if="(!editMode) && (getCanEdit())" @click="edit()">编辑</el-button>
        <el-button v-if="editMode && (getCanEdit())" :loading="saveLoading" @click="save()">保存</el-button>
        <el-button type="primary" @click="exportExcel">导出</el-button>
      </el-form-item>
    </el-form>
      <el-table :data="reportItems" style="width: 100%;" id="sale-table">
          <el-table-column
            prop="dateDescription"
            label="时间"
            min-width="150">
          </el-table-column>
        <el-table-column
          prop="plat"
          label="平台"
          min-width="100">
        </el-table-column>
          <el-table-column
            prop="visitorNum"
            label="访客数"
            min-width="80">
            <template slot-scope="scope">
              <el-input-number size="mini" class="edit-cell" :precision="0" :controls="false" v-if="editMode" v-model="scope.row.visitorNum" />
              <span v-if="!editMode">{{scope.row.visitorNum}}</span>
            </template>
          </el-table-column>
        <!-- <el-table-column
          prop="orderNum"
          label="订单数"
          min-width="80">
          <template slot-scope="scope">
          <el-input-number size="mini" class="edit-cell" :precision="0" :controls="false" v-if="editMode" v-model="scope.row.orderNum" />
          <span v-if="!editMode">{{scope.row.orderNum}}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="payPercent"
          label="支付转换率%"
          min-width="80">
           <template slot-scope="scope">
              <el-input-number size="mini" class="edit-cell" :precision="2" :controls="false" v-if="editMode" v-model="scope.row.payPercent" />
              <span v-if="!editMode">{{scope.row.payPercent}}</span>
            </template>
        </el-table-column>
          <el-table-column
            prop="saleValue"
            label="业绩"
            min-width="80">
            <template slot-scope="scope">
              <el-input-number size="mini" class="edit-cell" :precision="2" :controls="false" v-if="editMode" v-model="scope.row.saleValue" />
              <span v-if="!editMode">{{scope.row.saleValue}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="oldCustomerSalePercent"
            label="老客户业绩占比（%）"
            min-width="80">
            <template slot-scope="scope">
              <el-input-number size="mini" class="edit-cell" :precision="2" :controls="false" v-if="editMode" v-model="scope.row.oldCustomerSalePercent" />
              <span v-if="!editMode">{{scope.row.oldCustomerSalePercent}}</span>
            </template>
          </el-table-column>
        <el-table-column
          prop="zgValue"
          label="ZB系列业绩"
          min-width="80">
          <template slot-scope="scope">
            <el-input-number size="mini" class="edit-cell" :precision="2" :controls="false" v-if="editMode" v-model="scope.row.zgValue" />
            <span v-if="!editMode">{{scope.row.zgValue}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="valuePerOrder"
          label="客单价"
          min-width="80">
            <template slot-scope="scope">
              <el-input-number size="mini" class="edit-cell" :precision="2" :controls="false" v-if="editMode" v-model="scope.row.valuePerOrder" />
              <span v-if="!editMode">{{scope.row.valuePerOrder}}</span>
            </template>
        </el-table-column>
        <el-table-column
          prop="costAd"
          label="广告费"
          min-width="80">
          <template slot-scope="scope">
          <el-input-number size="mini" class="edit-cell" :precision="2" :controls="false" v-if="editMode" v-model="scope.row.costAd" />
          <span v-if="!editMode">{{scope.row.costAd}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="acos"
          label="ACOS%"
          min-width="80">
        </el-table-column>
        <el-table-column
          prop="costAct"
          label="营销活动支出"
          min-width="80">
          <template slot-scope="scope">
          <el-input-number size="mini" class="edit-cell" :precision="2" :controls="false" v-if="editMode" v-model="scope.row.costAct" />
          <span v-if="!editMode">{{scope.row.costAct}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="actPercent"
          label="营销活动占比%"
          min-width="80">
        </el-table-column>
      </el-table>
      <div style="clear: both;height:15px;width: 100%;"></div>
    </div>
</template>

<script>
  import DatePhase from  '@/components/sale/date-phase'
  import {dateUtil} from '@/utils/dateUtil'
  import dingMixin from  '@/mixins/ding'
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'

  export default {
    data () {
      return {
        datePhase:{
            dateType: 2,
            value:'',
            to:''
        },
        dialogVisible:false,
        plat: [],
        b2cMembers:[],
        plats: [],
        dingId: '',
        editMode: false,
        dataListLoading: false,
        saveLoading:false,
        reportItems:[]
      }
    },
    mixins: [dingMixin],
    components: {
      DatePhase
    },
    activated () {
      //this.getDataList()

    },
    created(){
      this.getPlats();
      this.getB2cMembers();
    },
    methods: {
      exportExcel(){
        this.$nextTick(function () {
          let wb = XLSX.utils.table_to_book(document.getElementById('sale-table'));
          let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
          try {
            FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'b2c.xlsx')
          } catch (e) {
            if (typeof console !== 'undefined') console.log(e, wbout)
          }
          return wbout;
        });
      },
      save(){
        this.saveLoading = true;
        let res = this.checkInputData()
        this.$http({
          url: this.$http.adornUrl('/sale/saveB2cData'),
          method: 'post',
          data: this.$http.adornData(res,false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.getReport()
          } else {
            this.$message({message: data.msg, type: 'error', duration: 3000})
          }
        }).finally(()=>{
          this.saveLoading = false
          this.editMode=false
        })
      },
      checkInputData(){
        let res = this.reportItems.filter(x=>x.plat!='总计' && x.plat!='B2C')
        return res
      },
      savePerm(){
        this.$http({
          url: this.$http.adornUrl('/sale/saveB2cPlat'),
          method: 'post',
          data: this.$http.adornData(this.plats,false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({message: '保存成功', type: 'success', duration: 3000})
          } else {
            this.$message({message: data.message, type: 'error', duration: 3000})
          }
        })
      },
      getB2cMembers(){
        this.$http({
          url: this.$http.adornUrl('/sale/listB2cMember'),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.b2cMembers = data.data
          } else {
            this.plats = []
          }
        })
      },
      getPlats(){
        this.$http({
          url: this.$http.adornUrl('/sale/listB2cPlat'),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.plats = data.data
          } else {
            this.plats = []
          }
        })
      },
      getPlatManager(platName){
        for(let plat of this.plats){
          if(plat.name == platName)
            return plat.remark
        }
        return ''
      },
      edit(){
        this.editMode=true;
      },
      getCanEdit(){
        if(this.reportItems.length>0 && this.reportItems[0].plat!='B2C'){
          if(dateUtil.nDayExpire(30, this.reportItems[0].createAt) && !this.isSaleLeader) {
            return false;
          }
          // if(this.getPlatManager(this.reportItems[0].plat)!=this.userInfo.dingId && !this.isSaleLeader){
          //   return false;
          // }
          return this.reportItems[0].dateType==2 || this.reportItems[0].dateType==3
        }
        return false
      },
      getUserPlats(){
        if(this.isSaleLeader || (this.userInfo.isLeaderDept && this.isB2cTeam) || this.userInfo.deptPath.indexOf('123098328')>=0){  // 
          return this.plats;
        }
        return this.plats.filter(x=>x.remark==this.userInfo.dingId);
      },
      // 获取数据列表
      getReport () {
        if(this.datePhase.value == null || this.datePhase.value == ''){
          this.$message({message: '请选择时间', type: 'error', duration: 3000})
          return
        }
        this.editMode = false
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/sale/listB2cData'),
          method: 'get',
          params: this.$http.adornParams({
            'datePhase': this.datePhase.value,
            'dateType': this.datePhase.dateType,
            'to': this.datePhase.to,
            'dingId': this.dingId,
            'plat': this.plat.join(',')
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.reportItems = data.data
          } else {
            this.reportItems = []
          }
        }).finally(()=>{
          this.dataListLoading = false
        })
      }
    },
    watch: {
      'dingId': {
        handler(newName, oldName) {
          if(this.dingId>''){
            this.plat = ''
          }
          //this.datePhase.to = ''
        }
      },
      'plat': {
        handler(newName, oldName) {
          if(this.plat>''){
            this.dingId = ''
          }
        }
      }
    }
  }
</script>
<style lang="scss">
  .el-table{
    font-size: 12px;
  }

  .edit-cell{
    width: 60px;
  }

  .el-input-number.is-without-controls .el-input__inner{
    padding: 0;
    text-align: left;
  }

</style>
